import "./index.less";
import Header from "@/components/header";
import { useState, useCallback, useEffect } from "react";
import { SearchBar, InfiniteScroll } from "antd-mobile";
import iphoneIcon from "@/assets/images/iphone.png";
import siteIcon from "@/assets/images/site.png";
import { Toast } from "antd-mobile";
import copy from "clipboard-copy";
import { getNearbyMerchants } from "@/api/nearby";
import { GeoWatcher } from "@/utils";
const size = 5;

function Nearby() {
  const [searchValue, setSearchValue] = useState("");
  const [hasMore, setHasMore] = useState(false);
  const [current, setCurrent] = useState(1);
  const [dataSource, setDataSource] = useState([]);

  // 加载更多商户数据
  const loadMore = useCallback(async () => {
    await getNearbyMerchantsData(current);
  }, [current]);

  // const handleMerchantSelect = (merchant) => {
  //   setSelectedMerchantId(merchant.id);
  //   console.log("选中的商户:", merchant);
  // };

  const handleCall = (merchantName, e) => {
    e.stopPropagation();
    Toast.show({ content: `正在拨通...`,maskClickable: false  });
    window.location.href = `tel:${merchantName}`;
  };

  const handleNavigate = (merchantName, e) => {
    e.stopPropagation(); // 防止事件冒泡
    copy(merchantName);
    Toast.show({ content: `复制成功`,maskClickable: false  });
  };

  const getNearbyMerchantsData = async (params = {}, page = current) => {
    // 使用封装的GeoWatcher获取位置
    const geoWatcher = new GeoWatcher({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 300000, // 5分钟缓存
    });

    const position = await geoWatcher.getPosition();
    const { latitude, longitude } = position.coords;
    const res = await getNearbyMerchants({
      latitude,
      longitude,
      current: page,
      size,
      ...params,
    });

    // 处理接口返回的数据格式
    const { data } = res;
    const { records, current: currentPage, pages } = data;
    console.log(records, "records", records, currentPage);
    if (currentPage === 1) {
      setDataSource(records);
    } else {
      setDataSource((prev) => [...prev, ...records]);
    }
    setCurrent(currentPage + 1); // 更新到下一页

    // 判断是否还有更多数据：当前页大于等于总页数时没有更多
    if (currentPage >= pages) {
      setHasMore(false);
    } else {
      setHasMore(true);
    }
  };

  useEffect(() => {
    getNearbyMerchantsData();
  }, []);

  return (
    <div className="nearby-page">
      <Header />
      <div className="nearby-content">
        {/* 顶部区域 */}
        <div className="top-section">
          <SearchBar
            placeholder="输入商户名称"
            value={searchValue}
            style={{
              "--border-radius": "100px",
            }}
            onChange={setSearchValue}
            onSearch={(val) =>
              getNearbyMerchantsData({ storeName: val, current: 1 })
            }
            autoFocus
          />
        </div>

        {/* 商户列表 */}
        <div className="merchant-list">
          {dataSource.map((merchant) => (
            <div
              key={`${merchant.id}-${merchant.brandId}${Math.random()}`}
              className="merchant-card"
              // onClick={() => handleMerchantSelect(merchant)}
            >
              <div className="merchant-info">
                <div className="merchant-name">{merchant.storeName}</div>

                <div className="merchant-status-row">
                  <div className="status-with-actions">
                    <div className="status-badge operating">营业中</div>
                    <div className="action-icons">
                      <img
                        src={siteIcon}
                        alt="位置"
                        className="action-icon"
                        onClick={(e) => handleNavigate(merchant.address, e)}
                      />
                      <img
                        src={iphoneIcon}
                        alt="电话"
                        className="action-icon"
                        onClick={(e) => handleCall(merchant.contactPhone, e)}
                      />
                    </div>
                  </div>
                </div>

                <div className="merchant-details">
                  <div className="operating-hours">
                    营业时间:
                    {merchant.openClock
                      ? `${merchant.openClock
                          .split("T")[1]
                          .substring(0, 5)} - ${merchant.closeClock
                          .split("T")[1]
                          .substring(0, 5)}`
                      : "暂无营业时间信息"}
                  </div>

                  <div className="distance-address">
                    直线距离:
                    {merchant.distance
                      ? `${(merchant.distance / 1000).toFixed(1)}km`
                      : "未知"}
                    | {merchant.address || "暂无地址信息"}
                  </div>
                </div>
              </div>

              {/* <div className="selection-indicator">
                <div
                  className={`selection-circle ${
                    selectedMerchantId === merchant.id ? "selected" : ""
                  }`}
                >
                  {selectedMerchantId === merchant.id && (
                    <span className="checkmark">✓</span>
                  )}
                </div>
              </div> */}
            </div>
          ))}

          <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
            {hasMore ? (
              <div className="loading-text">加载中...</div>
            ) : (
              <div className="no-more-text">没有更多了</div>
            )}
          </InfiniteScroll>
        </div>
      </div>
    </div>
  );
}

export default Nearby;
